package com.zhouixi.handler;
import com.zhouixi.repository.SessionManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/** 心跳处理器 */
@Component
@Slf4j
public class HeartbeatMessageHandler{
    private static final long HEARTBEAT_TIMEOUT = 30 * 1000; // 30秒超时
    private final ConcurrentHashMap<Long, Long> lastActiveTimeMap =
            new ConcurrentHashMap<>();

    @Resource
    private SessionManager sessionManager;

    private int size;

    public int getSize() {
        return size;
    }

    public void registerLastActiveTime(Long userId) {
        this.lastActiveTimeMap.put(userId,System.currentTimeMillis());
        ++size ;
    }

    public void scheduleHeartbeatCheck() {
        Set<Map.Entry<Long, Long>> entries = lastActiveTimeMap.entrySet();
        Iterator<Map.Entry<Long, Long>> iterator = entries.stream().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, Long> entry = iterator.next();
            Long userId = entry.getKey();
            Long lastActiveTime = entry.getValue();
            if (System.currentTimeMillis() - lastActiveTime > HEARTBEAT_TIMEOUT) {
                try {
                    // 移除 当前过期用户的会话时间
                    iterator.remove();
                    // 关闭会话，假如存在
                    sessionManager.removeSession(userId);
                } catch (Exception e) {
                    // 处理异常
                    log.error("heartbeat check error", e);
                }
            }
        };
    }
}